using UnityEngine;
using System.Collections.Generic;

[RequireComponent(typeof(RectTransform))]
public class UIRotator : MonoBehaviour
{
    [Header("旋转设置")]
    [Tooltip("旋转中心，默认为自身")]
    public RectTransform rotationCenter;
    [Tooltip("最小旋转角度（度）")]
    public float minAngle = -90f;
    [Tooltip("最大旋转角度（度）")]
    public float maxAngle = 90f;
    [Tooltip("旋转半径")]
    public float radius = 200f;
    [Tooltip("旋转速度（度/秒）")]
    public float rotationSpeed = 30f;
    [Tooltip("是否自动旋转")]
    public bool autoRotate = true;
    [Tooltip("旋转方向（正为顺时针，负为逆时针）")]
    public int rotationDirection = 1;
    [Tooltip("是否平滑旋转")]
    public bool smoothRotation = true;
    [Tooltip("平滑旋转的缓动系数")]
    [Range(0.1f, 20f)]
    public float smoothFactor = 5f;

    [Header("视觉效果")]
    [Tooltip("是否根据角度调整缩放")]
    public bool scaleWithAngle = true;
    [Tooltip("最大缩放值（正面元素）")]
    public float maxScale = 1f;
    [Tooltip("最小缩放值（侧面元素）")]
    public float minScale = 0.5f;
    [Tooltip("是否根据角度调整透明度")]
    public bool fadeWithAngle = true;
    [Tooltip("最大透明度（正面元素）")]
    [Range(0f, 1f)]
    public float maxAlpha = 1f;
    [Tooltip("最小透明度（侧面元素）")]
    [Range(0f, 1f)]
    public float minAlpha = 0.3f;

    [Header("UI元素")]
    [Tooltip("需要旋转的UI元素列表")]
    public List<RectTransform> uiElements = new List<RectTransform>();

    private float baseAngle = 0f; // 基础旋转角度，所有元素共享
    private float targetBaseAngle = 0f; // 目标基础旋转角度（用于平滑旋转）
    private float[] relativeAngles; // 每个元素相对于基础角度的偏移
    private CanvasGroup[] elementCanvasGroups; // 用于控制透明度

    private void Awake()
    {
        // 如果未设置旋转中心，使用自身作为中心
        if (rotationCenter == null)
        {
            rotationCenter = GetComponent<RectTransform>();
        }

        // 初始化CanvasGroup组件（用于控制透明度）
        InitializeCanvasGroups();
        
        // 初始化每个UI元素的相对角度
        InitializeRelativeAngles();
    }

    private void Start()
    {
        // 更新所有元素的初始位置
        UpdateAllElementsPosition();
    }

    private void InitializeCanvasGroups()
    {
        elementCanvasGroups = new CanvasGroup[uiElements.Count];
        
        for (int i = 0; i < uiElements.Count; i++)
        {
            if (uiElements[i] != null)
            {
                // 如果没有CanvasGroup组件则添加
                elementCanvasGroups[i] = uiElements[i].GetComponent<CanvasGroup>();
                if (elementCanvasGroups[i] == null)
                {
                    elementCanvasGroups[i] = uiElements[i].gameObject.AddComponent<CanvasGroup>();
                }
            }
        }
    }

    private void InitializeRelativeAngles()
    {
        if (uiElements.Count == 0) return;

        relativeAngles = new float[uiElements.Count];
        float angleRange = maxAngle - minAngle;
        
        // 如果只有一个元素，放在中间
        if (uiElements.Count == 1)
        {
            relativeAngles[0] = 0;
        }
        else
        {
            // 计算每个元素之间的角度间隔
            float angleStep = angleRange / (uiElements.Count - 1);
            
            for (int i = 0; i < uiElements.Count; i++)
            {
                // 计算相对角度（相对于基础角度的偏移）
                relativeAngles[i] = minAngle + i * angleStep;
            }
        }
    }

    private void Update()
    {
        if (autoRotate)
        {
            // 计算目标旋转角度
            targetBaseAngle += rotationSpeed * Time.deltaTime * rotationDirection;
            
            // 检查是否超出角度范围，如果超出则反向
            if (targetBaseAngle > maxAngle)
            {
                targetBaseAngle = maxAngle;
                rotationDirection *= -1;
            }
            else if (targetBaseAngle < minAngle)
            {
                targetBaseAngle = minAngle;
                rotationDirection *= -1;
            }
        }

        // 平滑旋转
        if (smoothRotation)
        {
            baseAngle = Mathf.Lerp(baseAngle, targetBaseAngle, smoothFactor * Time.deltaTime);
        }
        else
        {
            baseAngle = targetBaseAngle;
        }

        // 更新所有UI元素的位置
        UpdateAllElementsPosition();
    }

    /// <summary>
    /// 更新所有UI元素的位置
    /// </summary>
    private void UpdateAllElementsPosition()
    {
        for (int i = 0; i < uiElements.Count; i++)
        {
            UpdateElementPosition(i);
        }
    }

    /// <summary>
    /// 更新单个UI元素的位置
    /// </summary>
    private void UpdateElementPosition(int index)
    {
        if (index < 0 || index >= uiElements.Count || uiElements[index] == null) return;

        RectTransform element = uiElements[index];
        
        // 计算元素的当前角度（基础角度加上相对角度）
        float currentAngle = baseAngle + relativeAngles[index];
        
        // 将角度转换为弧度
        float rad = currentAngle * Mathf.Deg2Rad;
        
        // 计算新位置（相对于旋转中心）
        float x = Mathf.Cos(rad) * radius;
        float y = Mathf.Sin(rad) * radius;
        
        // 设置元素位置
        element.anchoredPosition = rotationCenter.anchoredPosition + new Vector2(x, y);

        // 根据角度调整缩放
        if (scaleWithAngle)
        {
            // 计算角度的绝对值（0度为正面）
            float angleAbs = Mathf.Abs(currentAngle);
            // 计算缩放比例（0度时最大，90度时最小）
            float scaleRatio = 1 - (angleAbs / 90f);
            float scale = Mathf.Lerp(minScale, maxScale, scaleRatio);
            element.localScale = Vector3.one * scale;
        }

        // 根据角度调整透明度
        if (fadeWithAngle && elementCanvasGroups[index] != null)
        {
            // 计算角度的绝对值（0度为正面）
            float angleAbs = Mathf.Abs(currentAngle);
            // 计算透明度比例（0度时最大，90度时最小）
            float alphaRatio = 1 - (angleAbs / 90f);
            elementCanvasGroups[index].alpha = Mathf.Lerp(minAlpha, maxAlpha, alphaRatio);
        }
    }

    /// <summary>
    /// 手动设置基础旋转角度
    /// </summary>
    public void SetBaseRotationAngle(float angle)
    {
        targetBaseAngle = Mathf.Clamp(angle, minAngle, maxAngle);
    }

    /// <summary>
    /// 增加基础旋转角度
    /// </summary>
    public void AddBaseRotationAngle(float deltaAngle)
    {
        targetBaseAngle = Mathf.Clamp(targetBaseAngle + deltaAngle, minAngle, maxAngle);
    }

    /// <summary>
    /// 切换旋转方向
    /// </summary>
    public void ToggleRotationDirection()
    {
        rotationDirection *= -1;
    }

    /// <summary>
    /// 切换自动旋转状态
    /// </summary>
    public void ToggleAutoRotate()
    {
        autoRotate = !autoRotate;
    }

    /// <summary>
    /// 添加UI元素到旋转列表
    /// </summary>
    public void AddUIElement(RectTransform element)
    {
        if (element != null && !uiElements.Contains(element))
        {
            uiElements.Add(element);
            InitializeCanvasGroups();
            InitializeRelativeAngles();
            UpdateAllElementsPosition();
        }
    }

    /// <summary>
    /// 从旋转列表中移除UI元素
    /// </summary>
    public void RemoveUIElement(RectTransform element)
    {
        if (uiElements.Contains(element))
        {
            uiElements.Remove(element);
            InitializeCanvasGroups();
            InitializeRelativeAngles();
            UpdateAllElementsPosition();
        }
    }

    // 在编辑器中绘制辅助线
    private void OnDrawGizmosSelected()
    {
        if (rotationCenter == null)
        {
            rotationCenter = GetComponent<RectTransform>();
        }

        if (rotationCenter != null)
        {
            // 转换旋转中心到世界坐标
            Vector3 centerWorldPos = rotationCenter.TransformPoint(rotationCenter.anchoredPosition);
            
            // 绘制旋转中心
            Gizmos.color = Color.yellow;
            Gizmos.DrawWireSphere(centerWorldPos, 10f);
            
            // 绘制旋转范围
            Gizmos.color = Color.cyan;
            DrawArc(centerWorldPos, minAngle, maxAngle, radius);
        }
    }

    // 绘制圆弧辅助线
    private void DrawArc(Vector3 center, float startAngle, float endAngle, float radius)
    {
        int segments = 30;
        float angleStep = (endAngle - startAngle) / segments;
        
        Vector3 prevPoint = center + Quaternion.Euler(0, 0, startAngle) * Vector3.right * radius;
        
        for (int i = 1; i <= segments; i++)
        {
            float angle = startAngle + i * angleStep;
            Vector3 currentPoint = center + Quaternion.Euler(0, 0, angle) * Vector3.right * radius;
            Gizmos.DrawLine(prevPoint, currentPoint);
            prevPoint = currentPoint;
        }
    }
}